<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="消息发送时间" prop="sendTime">
        <el-date-picker
          clearable
          v-model="queryParams.sendTime"
          type="datetime"
          value-format="yyyy-MM-dd"
          placeholder="请选择消息发送时间"
          :picker-options="sendTimeOptions">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="消息过期时间" prop="endTime">
        <el-date-picker
          clearable
          v-model="queryParams.endTime"
          type="datetime"
          value-format="yyyy-MM-dd"
          placeholder="请选择消息过期时间"
          :picker-options="endTimeOptions">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="是否确认" prop="isConfirmed">
        <el-select v-model="queryParams.isConfirmed" placeholder="请选择是否确认" clearable>
          <el-option
            v-for="dict in dict.type.is_confirmed"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="紧急程度" prop="urgencyLevel">
        <el-select v-model="queryParams.urgencyLevel" placeholder="请选择紧急程度" clearable>
          <el-option
            v-for="dict in dict.type.urgency_level"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ry/push:push:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ry/push:push:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ry/push:push:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ry/push:push:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <!-- 添加批量确定按钮 -->
        <el-button
          type="success"
          plain
          icon="el-icon-check"
          size="mini"
          :disabled="multiple"
          @click="handleConfirmBatch"
          v-hasPermi="['ry/push:push:confirm']"
        >批量确定
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="pushList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!-- <el-table-column label="自增主键" align="center" prop="id"/> -->
      <el-table-column label="客户" align="center" prop="customerName"/>
      <el-table-column label="推送内容" align="center" prop="content" width="300">
        <template slot-scope="scope">
          <div class="content-text" @click="handleViewFullContent(scope.row.content)">
            {{ truncateText(scope.row.content, 50) }}
            <el-link v-if="scope.row.content && scope.row.content.length > 50" type="primary" :underline="false">
              查看更多
            </el-link>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="是否确认" align="center" prop="isConfirmed">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.is_confirmed" :value="scope.row.isConfirmed"/>
        </template>
      </el-table-column>
      <el-table-column label="紧急程度" align="center" prop="urgencyLevel">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.urgency_level" :value="scope.row.urgencyLevel"/>
        </template>
      </el-table-column>
      <el-table-column label="消息发送时间" align="center" prop="sendTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.sendTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="消息过期时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="联系人" align="center" prop="contactPerson"/>
      <el-table-column
        v-if="!isReception"
        label="推送给"
        align="center"
        prop="pushName"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ry/push:push:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ry/push:push:remove']"
          >删除
          </el-button>
          <!-- 添加确定按钮 -->
          <el-button
            size="mini"
            type="success"
            icon="el-icon-check"
            :disabled="scope.row.isConfirmed !== 0"
            @click="handleConfirm(scope.row)"
            v-hasPermi="['ry/push:push:confirm']"
          >确定
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 修改后的对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20"> <!-- 使用栅格布局 -->
          <!-- 左列 -->
          <el-col :span="12">
            <el-form-item label="消息发送时间" prop="sendTime">
              <el-date-picker clearable
                              v-model="form.sendTime"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请选择消息发送时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="消息过期时间" prop="endTime">
              <el-date-picker clearable
                              v-model="form.endTime"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请选择消息过期时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="客户" prop="customerId">
              <el-select v-model="form.customerId" placeholder="请选择客户" filterable @change="handleCustomerChange">
                <el-option
                  v-for="customer in customerList"
                  :key="customer.id"
                  :label="customer.name"
                  :value="customer.id"
                />
              </el-select>
            </el-form-item>

            <!-- 紧急程度改为单选按钮组 -->
            <el-form-item label="紧急程度" prop="urgencyLevel">
              <el-radio-group v-model="form.urgencyLevel">
                <el-radio
                  v-for="dict in dict.type.urgency_level"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                  style="margin-right: 15px"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>


            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="form.contactPerson" placeholder="请输入联系人"/>
            </el-form-item>

          </el-col>
          <!-- 右列 -->
          <el-col :span="12">
            <el-form-item label="推送内容" prop="content">
              <el-input v-model="form.content" type="textarea" placeholder="请输入内容" rows="5" ref="contentInput"/>
              <el-button type="primary" size="mini" style="margin-top: 8px;" @click="openAIGenerateDialog">
                根据提示词分析该客户
              </el-button>
              <el-button type="primary" size="mini" style="margin-top: 8px; margin-left: 10px;"
                         :loading="aiAnalyzeLoading" :disabled="aiAnalyzeLoading || aiLoading"
                         @click="handleAIAnalyzeCustomer">AI自动分析该客户
              </el-button>
              <div v-if="aiLoading" style="color: #409EFF; margin-top: 4px;">AI生成中</div>
            </el-form-item>

            <el-form-item label="是否确认" prop="isConfirmed">
              <el-radio-group v-model="form.isConfirmed">
                <el-radio
                  v-for="dict in dict.type.is_confirmed"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                  style="margin-right: 15px"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="推送给" prop="pushName">
              <!-- 修改模板中的下拉框 -->
              <el-select
                v-model="form.pushId"
                filterable
                remote
                clearable
                reserve-keyword
                placeholder="请搜索客户或用户"
                :remote-method="remoteSearch"
                :loading="contactLoading"
                @change="handleContactChange"
              >
                <!-- 确保显示正确 -->
                <el-option
                  v-for="item in contactOptions"
                  :key="item.id"
                  :label="item.label || item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>

            <!-- 新增AI模型选择下拉框 -->
            <el-form-item label="选择模型" prop="selectedAiModel">
              <el-select
                v-model="form.selectedAiModel"
                placeholder="请选择AI模型"
                clearable
                style="width: 100%"
                @change="handleAiModelChange"
              >
                <el-option
                  v-for="model in aiModelOptions"
                  :key="model.id"
                  :label="model.modelName"
                  :value="model.modelName"
                />
              </el-select>
            </el-form-item>

          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 完整内容对话框 -->
    <el-dialog :title="fullContentDialogTitle" :visible.sync="fullContentDialogVisible" width="500px" append-to-body>
      <div class="full-content-display">
        {{ fullContentText }}
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="fullContentDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- AI生成内容对话框 -->
    <el-dialog :title="aiGenerateDialogTitle" :visible.sync="aiGenerateDialogVisible" width="600px" append-to-body
               :close-on-click-modal="false">
      <el-form :model="aiGenerateForm" ref="aiGenerateForm" label-width="80px" :rules="aiGenerateRules">
        <el-form-item label="AI结果">
          <el-input
            v-model="aiGenerateForm.result"
            type="textarea"
            :rows="6"
            placeholder="AI生成结果将显示在这里"
            ref="aiResultInput"
          ></el-input>
        </el-form-item>
        <el-form-item label="提示词">
          <el-input
            v-model="aiGenerateForm.prompt"
            type="textarea"
            :rows="4"
            placeholder="请输入AI生成内容的提示词，如：请根据客户{customerName}的消费记录，生成一条促销推送。"
          ></el-input>
          <el-button type="primary" size="mini" style="margin-top: 8px; float: right;" @click="sendAIGenerateRequest"
                     :loading="aiGenerateDialogLoading">发送
          </el-button>
          <div style="margin-top: 10px;">
            <el-tag
              v-for="tag in displayedPromptTags"
              :key="tag.promptId"
              effect="plain"
              size="small"
              style="margin-right: 10px; cursor: pointer;"
              @click="handleTagClick(tag.content)"
            >
              {{ tag.title }}
            </el-tag>
          </div>
          <div v-if="aiPromptList.length > maxVisiblePromptTags">
            <el-link
              v-if="!showAllPromptTags"
              type="primary"
              :underline="false"
              @click="toggleShowAllPromptTags"
              style="margin-top: 5px;"
            >展开更多
            </el-link>
            <el-link
              v-else
              type="primary"
              :underline="false"
              @click="toggleShowAllPromptTags"
              style="margin-top: 5px;"
            >收起
            </el-link>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="applyAIGeneratedContent" :disabled="!aiGenerateForm.result">应用</el-button>
        <el-button @click="cancelAIGenerateDialog">取消</el-button>
      </div>
    </el-dialog>

    <!-- 客户详情对话框 -->
    <el-dialog title="客户详情" :visible.sync="customerDetailDialogVisible" width="600px" append-to-body>
      <el-form ref="customerDetailForm" :model="customerDetailForm" label-width="120px" size="small">
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户ID:">
              <el-input v-model="customerDetailForm.customerId" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="消费水平:">
              <el-select v-model="customerDetailForm.consumptionLevel" disabled>
                <el-option
                  v-for="dict in customerDetailDicts.consumption_level"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="偏好皮肤:">
              <el-select v-model="customerDetailForm.preferenceSkin" disabled>
                <el-option
                  v-for="dict in customerDetailDicts.preference_skin"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="偏好项目:">
              <el-select v-model="customerDetailForm.preferenceProject" disabled>
                <el-option
                  v-for="dict in customerDetailDicts.preference_project"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品复购率:">
              <el-select v-model="customerDetailForm.productRepurchaseRate" disabled>
                <el-option
                  v-for="dict in customerDetailDicts.product_repurchase_rate"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格敏感度:">
              <el-select v-model="customerDetailForm.priceSensitivity" disabled>
                <el-option
                  v-for="dict in customerDetailDicts.price_sensitivity"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售阻力:">
              <el-select v-model="customerDetailForm.salesResistance" disabled>
                <el-option
                  v-for="dict in customerDetailDicts.sales_resistance"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="访问频率:">
              <el-select v-model="customerDetailForm.visitFrequency" disabled>
                <el-option
                  v-for="dict in customerDetailDicts.visit_frequency"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="敏感度:">
              <el-input v-model="customerDetailForm.sensitivity" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="AI原始分析结果:">
              <el-input
                v-model="aiAnalysisResult"
                type="textarea"
                :rows="5"
                disabled
                placeholder="AI原始分析结果"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="applyAIAnalysisToContent">应用</el-button>
        <el-button @click="customerDetailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPush,
  getPush,
  delPush,
  addPush,
  updatePush,
  confirmPush,
  confirmPushBatch,
  listContact,
  chatAI,
  analyzeCustomerAI
} from "@/api/ry/push/push";
import {listCustomer} from "@/api/ry/customer/customer";
import {listPrompts} from "@/api/ry/prompts/prompts";
import {listAiModel} from "@/api/ry/aiModel/aiModel";

export default {
  name: "Push",
  dicts: ['urgency_level', 'is_confirmed'],
  data() {
    return {
      isReception: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 消息推送表格数据
      pushList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sendTime: null,
        endTime: null,
        isConfirmed: null,
        urgencyLevel: null,
      },
      // 表单参数（修正：只有一个form对象）
      form: {
        id: null,
        sendTime: null,
        endTime: null,
        content: null,
        isConfirmed: null,
        urgencyLevel: null,
        contactPerson: null,
        pushName: null,
        pushId: null,       // 新增字段：推送目标ID
        pushType: null,     // 新增字段：推送目标类型
        pushObj: null,
        selectedAiModel: '', // 新增：选中的AI模型
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null
      },
      contactLoading: false,
      contactOptions: [],
      // 表单校验
      rules: {
        content: [
          {required: true, message: "推送内容不能为空", trigger: "blur"}
        ],
        urgencyLevel: [
          {required: true, message: "紧急程度不能为空", trigger: "change"}
        ],
        selectedAiModel: [
          {required: true, message: "请选择AI模型", trigger: "change"}
        ]
      },
      aiLoading: false, // AI生成加载状态
      aiController: null, // AI流式请求控制器
      timeoutDuration: 60000, // AI请求超时时间，单位毫秒 (60秒)
      customerList: [], // 客户列表
      fullContentDialogVisible: false, // 控制完整内容对话框的显示
      fullContentText: '', // 存储完整内容
      fullContentDialogTitle: '推送内容详情',
      aiAnalyzeLoading: false, // AI自动分析加载状态
      aiAnalyzeController: null, // AI自动分析流式请求控制器
      customerDetailDialogVisible: false, // 控制客户详情对话框的显示
      customerDetailForm: {}, // 存储客户详情数据
      customerDetailDicts: {
        consumption_level: [
          {label: '低', value: 1},
          {label: '中', value: 2},
          {label: '高', value: 3},
        ],
        preference_skin: [
          {label: '油性', value: 0},
          {label: '干性', value: 1},
          {label: '混合', value: 2},
        ],
        preference_project: [
          {label: '美白', value: 0},
          {label: '抗衰', value: 1},
          {label: '补水', value: 2},
        ],
        product_repurchase_rate: Array.from({length: 101}, (_, i) => ({label: `${i}%`, value: i})),
        price_sensitivity: [
          {label: '最低敏感', value: 0},
          {label: '低敏感', value: 1},
          {label: '中敏感', value: 2},
          {label: '稍高敏感', value: 3},
          {label: '高敏感', value: 4},
          {label: '最高敏感', value: 5},
        ],
        sales_resistance: Array.from({length: 101}, (_, i) => ({label: `${i}%`, value: i})),
        visit_frequency: [
          {label: '较少', value: 0},
          {label: '正常', value: 1},
          {label: '频繁', value: 2},
          {label: '忠实顾客', value: 3},
        ],
      },
      aiAnalysisResult: '', // 存储AI分析结果
      aiGenerateDialogVisible: false, // 控制AI生成内容对话框的显示
      aiGenerateDialogTitle: 'AI生成内容',
      aiGenerateDialogLoading: false, // AI生成内容对话框的加载状态
      aiGenerateController: null, // AI生成内容流式请求控制器
      aiGenerateForm: { // AI生成内容对话框表单
        prompt: '',
        result: '',
      },
      // AI生成内容对话框表单校验
      aiGenerateRules: {
        prompt: [
          {required: true, message: "请输入AI生成提示词", trigger: "blur"}
        ]
      },
      aiPromptList: [], // 存储从后端获取的AI提示词列表
      maxVisiblePromptTags: 5, // 默认显示的标签数量
      showAllPromptTags: false, // 控制是否显示所有标签
      aiModelOptions: [], // 新增：AI模型列表
    };
  },
// 修复computed属性中的角色判断
  computed: {
    // 确保角色标识符正确（根据实际系统配置）
    isReception() {
      return this.$store.getters.roles.includes('receptionist');
    },
    // 计算属性：根据showAllPromptTags决定显示多少标签
    displayedPromptTags() {
      return this.showAllPromptTags ? this.aiPromptList : this.aiPromptList.slice(0, this.maxVisiblePromptTags);
    }
  },

  created() {
    this.checkUserRole();
    this.getList();
    this.getCustomerList();
    this.getAiPromptList(); // 新增：获取AI提示词列表
    this.getAiModelList(); // 新增：获取AI模型列表
  },
  watch: {
    'form.content': function (newVal, oldVal) {
      // 当form.content更新时，自动滚动到底部
      this.$nextTick(() => {
        const textarea = this.$refs.contentInput ? this.$refs.contentInput.$refs.textarea : null;
        if (textarea) {
          textarea.scrollTop = textarea.scrollHeight;
        }
      });
    },
    'aiGenerateForm.result': function (newVal, oldVal) {
      // 当aiGenerateForm.result更新时，自动滚动到底部
      this.$nextTick(() => {
        const textarea = this.$refs.aiResultInput ? this.$refs.aiResultInput.$refs.textarea : null;
        if (textarea) {
          textarea.scrollTop = textarea.scrollHeight;
        }
      });
    }
  },
  methods: {
    // 检查用户角色
    checkUserRole() {
      const roles = this.$store.getters.roles;
      this.isReception = roles.includes('reception');
    },
    /** 查询消息推送列表 */
    getList() {
      this.loading = true;
      const params = {
        ...this.queryParams,
        // 前台用户强制添加过滤参数
        ...(this.isReception && {
          pushName: this.$store.getters.name,
          pushType: 'user'
        })
      };

      listPush(params).then(response => {
        this.pushList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // 保留角色相关参数
      if (this.isReception) {
        this.queryParams.pushName = this.$store.getters.name;
        this.queryParams.pushType = 'user';
      }
      this.handleQuery();
    },
    // 修正搜索方法
    remoteSearch(query) {
      if (query !== null && query !== undefined) {
        this.contactLoading = true;
        listContact({keyword: query}).then(response => {
          // 确保正确映射后端数据结构
          this.contactOptions = response.data.map(item => ({
            id: item.id,
            name: item.name, // 确保 name 属性存在
            type: item.type,
            label: item.name + (item.type === 'user' ? ' (用户)' : ' (客户)')
          }));
          this.contactLoading = false;
        }).catch(() => {
          this.contactOptions = [];
          this.contactLoading = false;
        });
      } else {
        this.contactOptions = [];
      }
    },
    // 添加联系人选择处理
    handleContactChange(id) {
      if (!id) {
        // 清除选择
        this.form.pushType = null;
        this.form.pushName = null;
        return;
      }

      // 直接使用映射数据，避免查找
      const selected = this.contactOptions.find(opt => opt.id === id);

      if (selected) {
        this.form.pushType = selected.type;
        this.form.pushName = selected.name; // 使用 name 属性
      } else {
        // 处理未找到的情况
        console.warn("未找到选中的联系人", id);
        this.form.pushType = null;
        this.form.pushName = null;
      }
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0];
      getPush(id).then(response => {
        this.form = response.data;

        // 修复：预加载当前联系人选项
        if (this.form.pushId) {
          listContact(this.form.pushName).then(res => {
            this.contactOptions = res.data.map(item => ({
              ...item,
              label: item.name + (item.type === 'user' ? ' (用户)' : ' (客户)')
            }));
            this.open = true;
            this.title = "修改消息推送";
          });
        } else {
          this.open = true;
          this.title = "修改消息推送";
        }
      });
    },
    // 截断文本方法
    truncateText(text, length) {
      if (!text) return '';
      return text.length > length ? text.substring(0, length) + '...' : text;
    },
    // 处理查看完整内容
    handleViewFullContent(content) {
      this.fullContentText = content;
      this.fullContentDialogVisible = true;
    },
    // 打开AI生成内容对话框
    openAIGenerateDialog() {
      if (!this.form.customerId) {
        this.$modal.msgWarning("请先选择客户！");
        return;
      }
      this.aiGenerateForm.prompt = ''; // 清空提示词
      this.aiGenerateForm.result = ''; // 清空结果
      this.aiGenerateDialogVisible = true;

      // 设置默认提示词，包含客户ID
      let defaultPrompt = `请根据客户`; // 基础提示
      const selectedCustomer = this.customerList.find(c => c.id === this.form.customerId);
      if (selectedCustomer && selectedCustomer.name) {
        defaultPrompt += `${selectedCustomer.name}`;
      }
      defaultPrompt += `的历史消费和偏好数据，生成一条营销推送内容。`;
      this.aiGenerateForm.prompt = defaultPrompt;
    },
    // 处理标签点击事件
    handleTagClick(content) {
      if (!this.form.customerId) {
        this.$modal.msgWarning("请先选择客户！");
        return;
      }
      // 将占位符替换为实际的客户ID和客户名称
      let finalPrompt = content.replace(/{customerId}/g, this.form.customerId);
      const selectedCustomer = this.customerList.find(c => c.id === this.form.customerId);
      if (selectedCustomer && selectedCustomer.name) {
        finalPrompt = finalPrompt.replace(/{customerName}/g, selectedCustomer.name);
      }
      this.aiGenerateForm.prompt = finalPrompt;
    },
    // 发送AI生成请求
    async sendAIGenerateRequest() {
      if (!this.form.customerId) {
        this.$modal.msgWarning("请先选择客户！");
        return;
      }
      // 手动校验AI模型是否选择
      if (!this.form.selectedAiModel) {
        this.$modal.msgWarning("请选择AI模型！");
        return;
      }

      // 修改：仅校验AI生成对话框的提示词字段
      this.$refs.aiGenerateForm.validate(async valid => {
        if (valid) {
          if (this.aiGenerateDialogLoading) return;

          this.aiGenerateDialogLoading = true;
          this.aiGenerateForm.result = ''; // 清空之前的生成结果
          if (this.aiGenerateController) this.aiGenerateController.abort();
          this.aiGenerateController = new AbortController();

          try {
            // 调用新的 chatAI 方法
            const reader = await chatAI({
              customerId: this.form.customerId,
              content: this.aiGenerateForm.prompt,
              modelName: this.form.selectedAiModel // 修改：将参数名称改为 modelName
            }, this.aiGenerateController.signal);

            const decoder = new TextDecoder('utf-8');
            let done = false;
            let aiText = '';
            while (!done) {
              const {value, done: doneReading} = await reader.read();
              done = doneReading;
              if (value) {
                aiText += decoder.decode(value, {stream: !done});
                this.aiGenerateForm.result = aiText; // 实时更新AI生成结果到对话框的输入框
              }
            }
          } catch (err) {
            if (err.name === 'AbortError') {
              console.log('AI生成请求已取消');
            } else {
              this.$message.error('AI生成失败');
              console.error('AI生成错误:', err);
            }
          } finally {
            this.aiGenerateDialogLoading = false;
            this.aiGenerateController = null; // 清除控制器
          }
        }
      });
    },
    // 将AI生成内容应用到推送内容
    applyAIGeneratedContent() {
      if (this.aiGenerateForm.result) {
        this.form.content = this.aiGenerateForm.result;
        this.aiGenerateDialogVisible = false;
      } else {
        this.$modal.msgWarning("没有AI生成内容可应用！");
      }
    },
    // 取消AI生成内容对话框
    cancelAIGenerateDialog() {
      this.aiGenerateDialogVisible = false;
      if (this.aiGenerateController) {
        this.aiGenerateController.abort(); // 取消正在进行的请求
        this.aiGenerateController = null;
      }
      this.aiGenerateForm.prompt = '';
      this.aiGenerateForm.result = '';
    },
    // AI自动分析客户
    async handleAIAnalyzeCustomer() {
      if (!this.form.customerId) {
        this.$modal.msgWarning("请先选择客户！");
        return;
      }
      // 新增：表单校验
      this.$refs.form.validate(async valid => {
        if (valid) {
          if (this.aiAnalyzeLoading) return;
          this.aiAnalyzeLoading = true;
          if (this.aiAnalyzeController) this.aiAnalyzeController.abort();
          this.aiAnalyzeController = new AbortController();
          try {
            // 调用新的 analyzeCustomerAI 方法
            const reader = await analyzeCustomerAI(this.form.customerId, this.form.selectedAiModel, this.aiAnalyzeController.signal); // 新增：传递AI模型名称

            const decoder = new TextDecoder('utf-8');
            let done = false;
            let aiText = '';
            while (!done) {
              const {value, done: doneReading} = await reader.read();
              done = doneReading;
              if (value) {
                aiText += decoder.decode(value, {stream: !done});
                this.aiAnalysisResult = aiText; // 实时更新AI分析结果到数据模型
              }
            }
            // 解析并填充客户详情表单
            try {
              const parsedData = JSON.parse(this.aiAnalysisResult);
              if (parsedData && parsedData.data && parsedData.data.data) {
                this.customerDetailForm = parsedData.data.data;
                this.customerDetailDialogVisible = true; // 弹出客户详情对话框
              } else {
                this.$message.error('AI自动分析结果格式不正确，无法填充客户详情！');
              }
            } catch (parseError) {
              this.$message.error('解析AI分析结果失败，无法填充客户详情！');
              console.error('解析AI分析结果失败:', parseError);
            }
          } catch (err) {
            if (err.name === 'AbortError') {
              console.log('AI自动分析请求已取消');
            } else {
              this.$message.error('AI自动分析失败');
              console.error('AI自动分析错误:', err);
            }
          } finally {
            this.aiAnalyzeLoading = false;
            this.aiAnalyzeController = null; // 清除控制器
          }
        }
      });
    },
    // 将AI分析结果应用到推送内容
    applyAIAnalysisToContent() {
      if (!this.customerDetailForm.customerId) {
        this.$modal.msgWarning("没有可应用的客户详情数据！");
        return;
      }

      const customerInfo = [];
      const fieldMapping = {
        customerId: '客户ID',
        consumptionLevel: '消费水平',
        preferenceSkin: '偏好皮肤',
        preferenceProject: '偏好项目',
        productRepurchaseRate: '产品复购率',
        priceSensitivity: '价格敏感度',
        salesResistance: '销售阻力',
        visitFrequency: '访问频率',
        sensitivity: '敏感度',
      };

      for (const key in fieldMapping) {
        if (this.customerDetailForm.hasOwnProperty(key)) {
          const label = fieldMapping[key];
          let value = this.customerDetailForm[key];

          // 新增确认方法
          // 根据字典获取描述性文本
          if (this.customerDetailDicts[this.camelToSnakeCase(key)]) {
            const dict = this.customerDetailDicts[this.camelToSnakeCase(key)];
            const option = dict.find(item => item.value === value);
            value = option ? option.label : value;
          } else if (key === 'productRepurchaseRate' || key === 'salesResistance') {
            value = `${value}%`; // 特殊处理百分比
          }

          customerInfo.push(`${label}: ${value}`);
        }
      }

      this.form.content = "客户分析结果：\n" + customerInfo.join("\n");
      this.customerDetailDialogVisible = false; // 关闭客户详情对话框
    },
    camelToSnakeCase(name) {
      return name.replace(/([A-Z])/g, "_$1").toLowerCase();
    },
    // 新增确认方法
    handleConfirm(row) {
      // 检查消息是否已经确认
      if (row.isConfirmed !== 0) {
        this.$modal.msgWarning("该消息已确认，无需重复操作");
        return;
      }
      this.$modal.confirm('确认要标记该消息为"已确认"吗？').then(() => {
        confirmPush(row.id).then(response => {
          this.$modal.msgSuccess("确认成功");
          this.getList();
        });
      }).catch(() => {
      });
    },

    // 修改后的批量确认方法
    handleConfirmBatch() {
      // 过滤出尚未确认的消息ID
      const unconfirmedIds = this.ids.filter(id => {
        const row = this.pushList.find(item => item.id === id);
        return row && row.isConfirmed === 0;
      });

      // 如果所有选中消息都已确认
      if (unconfirmedIds.length === 0) {
        this.$modal.msgWarning("选中的消息都已确认，无需重复操作");
        return;
      }

      // 提示仅确认尚未确认的消息
      const confirmationText = unconfirmedIds.length === this.ids.length
        ? `确认要将选中的 ${unconfirmedIds.length} 条消息标记为"已确认"吗？`
        : `选中了 ${this.ids.length} 条消息，其中 ${this.ids.length - unconfirmedIds.length} 条已确认，仅确认 ${unconfirmedIds.length} 条未确认消息吗？`;

      this.$modal.confirm(confirmationText).then(() => {
        confirmPushBatch(unconfirmedIds).then(response => {
          const successMsg = unconfirmedIds.length === this.ids.length
            ? "批量确认成功"
            : "部分消息确认成功（已确认的消息未重复操作）";

          this.$modal.msgSuccess(successMsg);
          this.getList();
        });
      }).catch(() => {
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sendTime: null,
        endTime: null,
        content: null,
        isConfirmed: 0, // 默认未确认
        urgencyLevel: null,
        contactPerson: null,
        pushName: null,
        customerId: null,
        customerName: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
        pushId: null,
        pushType: null,
        pushObj: null,
        selectedAiModel: '' // 新增：选中的AI模型
      };
      this.contactOptions = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加消息推送";

      // 新增：初始化加载联系人列表（空搜索）
      this.$nextTick(() => {
        this.remoteSearch('');
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePush(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPush(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除消息推送编号为"' + ids + '"的数据项？').then(function () {
        return delPush(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ry/push/push/export', {
        ...this.queryParams
      }, `push_${new Date().getTime()}.xlsx`)
    },
    getCustomerList() {
      listCustomer({pageNum: 1, pageSize: 100000}).then(res => {
        this.customerList = res.rows || [];
      });
    },
    // 新增：获取AI提示词列表
    getAiPromptList() {
      listPrompts({pageNum: 1, pageSize: 100000}).then(response => {
        this.aiPromptList = response.rows || [];
      }).catch(error => {
        console.error("获取AI提示词列表失败", error);
        this.$modal.msgError("获取AI提示词列表失败");
      });
    },
    // 新增：切换显示所有提示词标签
    toggleShowAllPromptTags() {
      this.showAllPromptTags = !this.showAllPromptTags;
    },
    handleCustomerChange(val) {
      const selected = this.customerList.find(c => c.id === val);
      if (selected) {
        this.form.customerName = selected.name;
        this.$modal.msgSuccess(`已选择客户：${selected.name}`); // 新增：客户选择提示
      } else {
        this.form.customerName = '';
        this.$modal.msgWarning("客户选择已清空。"); // 新增：客户选择清空提示
      }
    },
    // 新增：AI模型选择处理
    handleAiModelChange(val) {
      const selectedModel = this.aiModelOptions.find(model => model.modelName === val);
      if (selectedModel) {
        this.$modal.msgSuccess(`已选择AI模型：${selectedModel.modelName}`);
      } else {
        this.$modal.msgWarning("AI模型选择已清空。");
      }
    },
    getAiModelList() {
      listAiModel({pageNum: 1, pageSize: 100000}).then(response => {
        this.aiModelOptions = response.rows || [];
      }).catch(error => {
        console.error("获取AI模型列表失败", error);
        this.$modal.msgError("获取AI模型列表失败");
      });
    },
  }
};
</script>

<style scoped>
.content-text {
  cursor: pointer;
  white-space: nowrap; /* Prevent text from wrapping */
  overflow: hidden; /* Hide overflow content */
  text-overflow: ellipsis; /* Add ellipsis for overflow */
}

.full-content-display {
  white-space: normal; /* Allow text to wrap */
  word-wrap: break-word; /* Break long words */
  overflow-y: auto; /* Enable scroll if content is too long */
  max-height: 400px; /* Limit height and enable scrolling */
}
</style>
